package com.tedu.pj.sys.controller;

import com.tedu.pj.common.pojo.Response;
import com.tedu.pj.sys.pojo.SysUser;
import com.tedu.pj.sys.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.util.Map;

/**
 * <p>
 *
 * </p>
 *
 * @author Song
 * @since 2020/10/20
 */
@RestController
@RequestMapping("/user/")
public class SysUserController {


    @Autowired
    SysUserService sysUserService;

    @RequestMapping("doFindPageObjects")
    public Response doFindPageObjects(String username, Integer pageCurrent) {
        return new Response(sysUserService.findPageObjects(username, pageCurrent));
    }

    @RequestMapping("doValidById")
    public Response doValidById(Integer id, Integer valid) {
        sysUserService.validById(id, valid);
        return new Response("update ok");
    }

    @RequestMapping("doSaveObject")
    public Response doSaveObject(SysUser entity, Integer[] roleIds) {
        sysUserService.saveObject(entity, roleIds);
        return new Response("save ok");
    }

    @RequestMapping("doFindObjectById")
    public Response doFindObjectById(Integer id) {
        Map<String, Object> map = sysUserService.findObjectById(id);
        return new Response(map);
    }

    @RequestMapping("doUpdateObject")
    public Response doUpdateObject(SysUser entity, Integer[] roleIds) {
        sysUserService.updateObject(entity, roleIds);
        return new Response("update ok");
    }

    @RequestMapping("doUpdatePassword")
    public Response doUpdatePassword(String pwd, String newPwd, String cfgPwd) {
        sysUserService.updatePassword(pwd, newPwd, cfgPwd);
        return new Response("update ok");
    }

    @RequestMapping("doLogin")
    public Response doLogin(boolean isRememberMe,
                            @NotBlank(message = "用户名不能为空") String username,
                            @NotBlank(message = "密码不能为空") String password) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        if (isRememberMe) {
            token.setRememberMe(true);
        }
        subject.login(token);
        return new Response("login ok");
    }
}
